Sometimes, when we deal with images stored in database BLOB we will come across situations where we need to convert between BitMap object to byte[] and vice versa. This code snippet will help us to achieve it.
Byte[] to Bitmap Object
Stream str = new MemoryStream((Byte[])dr[0]);
Bitmap loBMP = new Bitmap(str);
In the above code, dr[0] is the datareader object that fetches the byte array from the database.
BitMap Object to byte[]
MemoryStream ms = new MemoryStream();
bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] bmpBytes = ms.GetBuffer();
bmpOut.Dispose();
ms.Close();
OR
byte[] bmpBytes = (byte[])System.ComponentModel.TypeDescriptor.GetConverter(bmpOut).ConvertTo(bmpOut, typeof(byte[]));
In the above code, bmpOut is the BitMap Object.
Include System.IO and System.Drawing namespace for the above code to work.
|